﻿using DevExpress.XtraGrid.Views.Grid;
using Fatura;
using SpreadsheetGear;
using System;
using System.Data;
using System.IO;
using System.Windows.Forms;

namespace Fatura
{
    public partial class XImportWizard : XForm
    {
        public string Header = string.Empty;
        private bool MasterDetailEnabled = false;
        public delegate void FileDoneEventHandler(DataSet Data, string FileName);
        public event FileDoneEventHandler FileDone;
        public delegate void ProcessDoneEventHandler();
        public delegate void ProcessStartEventHandler();
        public event ProcessDoneEventHandler ProcessDone;
        public event ProcessStartEventHandler ProcessStart;

        public GridView MasterGrid
        {
            get
            {
                return gvMaster;
            }
        }

        public GridView DetailGrid
        {
            get
            {
                return gvDetail;
            }
        }

        public XImportWizard()
        {
            InitializeComponent();
        }

        public void Init(string Header, bool MasterDetailEnabled)
        {
            this.Text =
            this.Header = Header;
            //txtInfo.Caption = Header;

            this.MasterDetailEnabled = MasterDetailEnabled;
            this.splitter.SizeChanged += splitter_SizeChanged;

            if (!MasterDetailEnabled)
                splitter.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Panel1;
        }

        private int splitterWidthPercentage = 50;
        public int SplitterWidthPercentage
        {
            get
            {
                return splitterWidthPercentage;
            }
            set
            {
                splitterWidthPercentage = value;
                splitter.SplitterPosition = splitter.Width / 100 * SplitterWidthPercentage;
            }
        }

        private void splitter_SizeChanged(object sender, EventArgs e)
        {
            splitter.SplitterPosition = splitter.Width / 100 * SplitterWidthPercentage;
        }


        public static DataSet ReadExcel(FileInfo file)
        {
            string filename = file.FullName;

            if (file.Name.ToLower().EndsWith(".csv"))
            {
                string content = File.ReadAllText(filename);
                if (content.ToCharArray()[content.Length - 1] == (char)26)  //son satırdaki ok: EOF
                    content = content.Substring(0, content.Length - 1);

                if (content.Contains(";"))
                    content = "\"" + content.Replace(";", "\",\"").Replace(Environment.NewLine, "\"" + Environment.NewLine + "\"") + "\"";

                filename = "x.csv";
                File.WriteAllText(filename, content);
            }

            IWorkbook Workbook = SpreadsheetGear.Factory.GetWorkbook(filename);

            // Set summary total for all regions.

            DataSet ds = Workbook.GetDataSet(SpreadsheetGear.Data.GetDataFlags.NoColumnHeaders | SpreadsheetGear.Data.GetDataFlags.NoColumnTypes);

            //DataSet ds = Workbook.GetDataSet(SpreadsheetGear.Data.GetDataFlags.NoColumnTypes);
            //string Message = ds.Tables[0].Serialize();


            IWorksheet worksheet = Workbook.Worksheets[0];
            DataTable dtDovizCinsi = GetDovizCinsi(worksheet.UsedRange);
            ds.Tables.Add(dtDovizCinsi);

            return ds;

            /*
             * http://peterkellner.net/2010/09/12/spreadsheetgear-to-the-rescue-export-excel-file/
             * 
             * 
            IWorkbookSet workbookSet = SpreadsheetGear.Factory.GetWorkbookSet();
            IWorkbook workbook = workbookSet.Workbooks.Open(@"C:\file.csv");
            IRange cells = workbook.Worksheets[0].UsedRange;
            */
        }

        private static DataTable GetDovizCinsi(IRange range)
        {
            bool outerBreak = false;
            string DovizCinsi = "";
            for (int i = 0; i < range.RowCount && !outerBreak; i++)
                for (int j = 0; j < range.ColumnCount && !outerBreak; j++)
                {
                    string format = range.Cells[i, j].NumberFormat;
                    if (format.Contains("EUR"))
                    {
                        DovizCinsi = "EUR";
                        outerBreak = true;
                    }
                    else if (format.Contains("USD"))
                    {
                        DovizCinsi = "USD";
                        outerBreak = true;
                    }
                    else if (format.Contains("GBP"))
                    {
                        DovizCinsi = "GPB";
                        outerBreak = true;
                    }
                }

            DataTable dtDovizCinsi = new DataTable();
            dtDovizCinsi.Columns.Add("DovizCinsi", typeof(string));
            dtDovizCinsi.Rows.Add(DovizCinsi);

            return dtDovizCinsi;
        }

        private void BtnProcessFile_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;

                using (OpenFileDialog fdOpen = new OpenFileDialog())
                {
                    fdOpen.Filter = "Excel Files (*.xls*;*.csv)|*.xls*;*.csv";
                    //fdOpen.Filter = "Excel Files|*.xls*|CSV files|*.csv";
                    fdOpen.FilterIndex = 1;
                    fdOpen.Multiselect = true;
                    if (fdOpen.ShowDialog(AppSession.MainForm) == DialogResult.OK)
                    {
                        if (ProcessStart != null)
                            ProcessStart();

                        int i = 0;
                        DataSet ds = new DataSet();
                        foreach (string FileName in fdOpen.FileNames)
                        {
                            //this.Text = Header + " (" + FileName + ")";

                            foreach (DataTable dt in ReadExcel(new FileInfo(FileName)).Tables)
                            {
                                if (ds.Tables.Contains(dt.TableName))
                                    dt.TableName += "_" + (++i).ToString();

                                ds.Tables.Add(dt.Copy());
                            }
                        }

                        //TODO: yukarıya mı alalım? sadece bir tabloyu işliyor Monti_tip1'de!
                        if (fdOpen.FileNames.Length > 0)
                            if (FileDone != null)
                                FileDone(ds, fdOpen.FileNames[0]);

                        if (ProcessDone != null)
                            ProcessDone();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                btnSave.Enabled = true;
                Cursor = Cursors.Default;
            }
        }

        private void XImportWizard_Load(object sender, EventArgs e)
        {
            btnProcessFile.ItemClick += BtnProcessFile_ItemClick;
        }

    }
}
